package com.zkzx.operation.api.config.authorization;

import com.zkzx.operation.api.service.authorization.MyUserDetails;
import com.zkzx.util.json.JSONResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * 可以自定义token信息
 * Created by young on 2021/4/26.
 */
@Slf4j
public class RedisTokenEnhancer implements TokenEnhancer {

    private final static String HEADER_USER = "userId";

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String, Object> info = new HashMap<>();
        //自定义的所有信息都写入info即可
        MyUserDetails myUserDetails =  (MyUserDetails) oAuth2Authentication.getPrincipal();
        info.put(HEADER_USER, myUserDetails.getUsername());
        log.info("用户登录信息：{}",JSONResultUtil.object2JSON(oAuth2Authentication.getUserAuthentication()));
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }
}
